﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using GuRenFang.Service.Entity;
using GuRenFang.Service.IBiz;

namespace GuRenFang.Controllers.Management
{
    public class NewsController : Controller
    {
        private readonly INewsBiz _newService;

        public NewsController(INewsBiz newsService)
        {
            _newService = newsService;
        }


        [Authorize]
        public ActionResult List(int? page = 1, int? pageSize = 10)
        {
            ViewBag.Model = "News";

            short size = Convert.ToInt16(ConfigurationManager.AppSettings["AdminpageSize"]);

            int totalRecord = 0;
            IEnumerable<News> news = _newService.GetNewsByPages(out totalRecord, pageIndex: page.GetValueOrDefault(),
                                                                pageSize: size, orderFiled: "");

            var item = new PageItem
                           {
                               CurrentPage = page.GetValueOrDefault(),
                               TotalRecords = totalRecord,
                               TotalPages = (totalRecord%size == 0) ? totalRecord/size : totalRecord/size + 1,
                               ControllerName = "News",
                               ActionName = "List"
                           };

            var viewModels = new Pager<News> {DataSource = news, Item = item};

            return View(viewModels);
        }

        [Authorize]
        public ActionResult Edit(int? id = 1)
        {
            ViewBag.Model = "News";

            News newsItem = _newService.GetById(id.GetValueOrDefault());
            return View(newsItem);
        }

        [Authorize]
        [HttpPost]
        [ValidateInput(false)]
        public RedirectToRouteResult Edit(News news)
        {
            if (ModelState.IsValid)
            {
                news.CreatedTime = DateTime.Now;
                _newService.Update(news);
            }
            return RedirectToAction("List");
        }

        [Authorize]
        public ActionResult Add()
        {
            ViewBag.Model = "News";
            return View();
        }

        [Authorize]
        [HttpPost]
        [ValidateInput(false)]
        public RedirectToRouteResult Add(News news)
        {
            if (ModelState.IsValid)
            {
                news.CreatedTime = DateTime.Now;
                news.ReadTimes = 1;
                _newService.Create(news);
            }
            return RedirectToAction("List");
        }

        [Authorize]
        public ActionResult Delete(int id)
        {
            _newService.Delete(id);
            return RedirectToAction("List");
        }
    }
   
}
